package dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import beans.Branch;
import beans.Expense;
import beans.Express;

import utils.HibernateUtil;




public class ExpenseDao {
	private SessionFactory sessionFactory;

	public ExpenseDao() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}

	Transaction tr = null;
	
	/**
	 * 删除扣费信息
	 */
	public void delete(Expense expense) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.delete(expense);
		tr.commit();
		session.close();
	}
	
	/**
	 * 修改扣费信息
	 */
	public void edit(Expense expense) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.update(expense);
		tr.commit();
		session.close();
	}
	
	/**
	 * 保存新增扣费信息
	 */
	public void save(Expense expense) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.save(expense);
		tr.commit();
		session.close();
	}
	
	/**
	 * 返回所有扣费信息
	 */
	public List<Expense> getAllExpense(Branch branch){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Expense.class);
		c.add(Restrictions.eq("branch", branch));
		List<Expense> expenses=c.list();
		tr.commit();
		session.close();
		return expenses;
	}
	
	/**
	 * 返回所有扣费信息
	 */
	public List<Expense> checkSize(Expense expense){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Expense.class);
		c.add(Restrictions.eq("branch", expense.getBranch()));
		c.add(Restrictions.eq("express", expense.getExpress()));
		List<Expense> expenses=c.list();
		tr.commit();
		session.close();
		return expenses;
	}
	
	/**
	 * 返回所有扣费信息
	 */
	public List<Expense> getAllExpense(Express express){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Expense.class);
		c.add(Restrictions.eq("express", express));
		List<Expense> expenses=c.list();
		tr.commit();
		session.close();
		return expenses;
	}
	
	/**
	 * 返回所有扣费信息
	 */
	public List<Expense> getAllExpense(){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Expense.class);
		c.add(Restrictions.eq("checked", 0));
		List<Expense> expenses=c.list();
		tr.commit();
		session.close();
		return expenses;
	}

	/**
	 * 通过ID返回指定扣费信息
	 * 
	 * @return
	 */
	public Expense getExpenseById(int expenseId) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Expense expense = (Expense) session.get(Expense.class, expenseId);
		tr.commit();
		session.close();
		return expense;
	}
}
